# -*- encoding: utf-8 -*-
##############################################################################
#
# Copyright (c) 2011 ZestyBeanz Technologies Pvt. Ltd.
#    (http://wwww.zbeanztech.com) All Rights Reserved.
#     vishnu@zbeanztech.com
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
###############################################################################

from osv import fields, osv
from datetime import datetime
import time
from tools.translate import _
import binascii
import tools
import email.utils
from email.header import decode_header, Header
from dateutil.parser import parse



class unsubscribed_users(osv.osv):
    _name = "unsubscribed.users"
    _description = "Unsubscribed Users List"
    _inherit = ['mailgate.thread']
    _columns = {
                'name': fields.char('Name', size=64,),
                'email_from' : fields.char('Email Address',size=64),
                'email_date' : fields.datetime('Date'),
                'partner_id' : fields.many2one('res.partner','Partner')
                }

    def _decode_header(self, text):
            """Returns unicode() string conversion of the the given encoded smtp header"""
            if text:
                text = decode_header(text.replace('\r', ''))
                return ''.join([tools.ustr(x[0], x[1]) for x in text])

    def message_new(self, cr, uid, msg, context=None):
        """
        Automatically calls when new email message arrives

        @param self: The object pointer
        @param cr: the current row, from the database cursor,
        @param uid: the current user’s ID for security checks
        """
        mailgate_pool = self.pool.get('email.server.tools')
        attach_obj = self.pool.get('ir.attachment')

        subject = msg.get('subject')
        body = msg.get('body')
        msg_from = msg.get('from')
        date =self._decode_header(msg.get('date'))
        maildate = parse(date)
        addr = email.utils.parseaddr(msg_from)[1]
        vals = {
            #'name': subject,
            'email_from': addr,
            'email_date' : maildate
        }


        res = mailgate_pool.get_partner(cr, uid, msg.get('from'))
        if res:
            vals.update(res)
        res = self.create(cr, uid, vals, context=context)
        mem_ids = self.pool.get('mail.group.member').search(cr,uid,[('email','=',vals['email_from'])])
        self.pool.get('mail.group.member').write(cr,uid,mem_ids,{'not_interested':True})


        return res



unsubscribed_users()


